// Created by Joe on 2017/7/21.

app.controller(
    'SocialSecurityController',
    [
        'KEY', 'config', '$scope', '$location', '$filter', 'UserService', 'SocialSecurityService',
        function (KEY, config, $scope, $location, $filter, UserService, SocialSecurityService) {
            init();

            function init() {
                // set pension name map
                $scope.PensionMap = {
                    dwmc: {name: '单位名称', disIndex: 0},
                    nf: {name: '年度', disIndex: 1},
                    jfys: {name: '累计缴费月数', disIndex: 2},
                    dwjze: {name: '单位累计', disIndex: 3},
                    grjze: {name: '个人累计', disIndex: 4},
                    dnjfys: {name: '当年缴费月数', disIndex: 5},
                    dndwjze: {name: '当年单位划入', disIndex: 6},
                    dndwlx: {name: '当年单位利息', disIndex: 7},
                    dngrjze: {name: '当年个人划入', disIndex: 8},
                    dngrlx: {name: '当年个人利息', disIndex: 9}
                };

                // set move
                $scope.position = config.SocialSecurity;

                // set page and panel
                $scope.page = ['home', 'pension', 'medical', 'retirement', 'unemployment', 'mask'];
                $scope.limit = {pension: 5, medical: 5};
                $scope.panel = {show: false, empty: false, load: false, mask: false};

                // control
                // @pl: pension list index
                // @pa: pension arrow status flag
                // @ml: medial list index
                // @mf: mask show flag
                $scope.control = {page: 0, pl: 0, pa: '', ml: 0, ma: '', mf: false};

                // current position
                $scope.cp = $scope.position[$scope.page[$scope.control.page]];

                // set page stack and cache
                $scope.pageStack = [];
                $scope.pageCache = '';

                // set focus
                $scope.focus = {ci: 'ss-h1'};

                // add social-security logic
                addLogic();

                // merge logic for common repeat
                $scope.logic = {
                    total: [$scope.gotoPension, $scope.gotoMedical, $scope.gotoRetirement, $scope.gotoUnemployment]
                };

                // set data
                $scope.data = {
                    total: [{}, {}, {}, {}],
                    pension: [],
                    curPension: [],
                    filter: ['', '', '', ''],
                    filterDis: ['197001', $filter('mul_date')(new Date(), 5)],
                    medical: [],
                    curMedical: []
                };

                // set data-bind map
                $scope.bindMap = {
                    'ss-mk1': 0,
                    'ss-mk2': 1,
                    'ss-mk3': 2,
                    'ss-mk4': 3
                };

                // get info
                $scope.panel.mask = true;
                $scope.panel.load = true;
                SocialSecurityService.getTotalInfo()
                    .then(function (info) {
                        info.total.forEach(function (item, index) {
                            if (item.data === '暂无数据') {
                                $scope.data.total[index] = {
                                    info: '暂无数据',
                                    status: 2,
                                    count: ''
                                };
                            } else {
                                $scope.data.total[index] = {
                                    info: '当前余额',
                                    status: 1,
                                    count: '￥' + item.data.substr(3)
                                };
                            }
                        });

                        $scope.panel.mask = false;
                        $scope.panel.load = false;
                    });

                // ele action
                $scope.move = function (evt, cb) {
                    if (evt.keyCode === KEY.LEFT ||
                        evt.keyCode === KEY.RIGHT ||
                        evt.keyCode === KEY.UP ||
                        evt.keyCode === KEY.DOWN ||
                        evt.keyCode === KEY.BACK ||
                        evt.keyCode === KEY.ENTER)
                        evt.preventDefault();

                    if ($scope.control.page === 0 && $scope.panel.load) return;

                    switch (evt.keyCode) {
                        case KEY.LEFT:
                            moveShim('left');
                            break;
                        case KEY.UP:
                            moveShim('up');
                            break;
                        case KEY.RIGHT:
                            moveShim('right');
                            break;
                        case KEY.DOWN:
                            if (evt.target.id === 'ss-m1' && $scope.data.medical.length > $scope.limit.medical) {
                                document.getElementById('ss-m1').blur();
                            } else {
                                moveShim('down');
                            }
                            break;
                        case KEY.BACK:
                            if ($scope.control.mf) {
                                var eleIndex = $scope.bindMap[evt.target.id];
                                if (eleIndex !== undefined && $scope.data.filter[eleIndex]) {
                                    var len = $scope.data.filter[eleIndex].length;
                                    $scope.data.filter[eleIndex] = $scope.data.filter[eleIndex].substr(0, len - 1);
                                }
                            }
                            break;
                        case KEY.ENTER:
                            cb instanceof Function && cb();
                            break;
                    }
                };

                // global action
                document.addEventListener('keydown', globalAction);
            }

            function addLogic() {
                // open medical filter
                $scope.openMF = function () {
                    if ($scope.panel.load) return;
                    $scope.control.mf = true;
                    $scope.panel.empty = false;
                    $scope.cp = $scope.position['mask'];
                    resetFocus();
                };

                // close medical filter
                $scope.closeMF = function (direct) {
                    return function () {
                        if (direct) $scope.panel.empty = $scope.data.medical.length === 0;
                        ;
                        $scope.control.mf = false;
                        $scope.cp = $scope.position['medical'];
                        resetFocus();
                    };
                };

                // search
                $scope.medicalSearch = function () {
                    var year = new Date().getFullYear();
                    var yearCheck = $scope.data.filter[0].length < 4
                        || parseInt($scope.data.filter[0], 10) > year
                        || $scope.data.filter[2].length < 4
                        || parseInt($scope.data.filter[2], 10) > year;
                    var monthCheck = $scope.data.filter[1].length === 0
                        || parseInt($scope.data.filter[1], 10) > 12
                        || $scope.data.filter[3].length === 0
                        || parseInt($scope.data.filter[3], 10) > 12;
                    var combineCheck = parseInt($scope.data.filter[2], 10) < parseInt($scope.data.filter[0], 10)
                        || (parseInt($scope.data.filter[2], 10) === parseInt($scope.data.filter[0], 10)
                        && $scope.data.filter[3] < parseInt($scope.data.filter[1], 10));

                    if (yearCheck || monthCheck || combineCheck) {
                        $scope.panel.show = true;
                        return;
                    }

                    var start = $scope.data.filter[0] + padding($scope.data.filter[1]);
                    var end = $scope.data.filter[2] + padding($scope.data.filter[3]);
                    $scope.data.filterDis[0] = start;
                    $scope.data.filterDis[1] = end;
                    $scope.gotoMedical(start, end, true);
                    $scope.closeMF()();
                };

                // goto pension and get pension info
                $scope.gotoPension = function () {
                    pageSwitch(1)();
                    // reset here, but it's not necessary
                    $scope.data.pension = [];
                    $scope.data.curPension = [];
                    $scope.control.pl = 0;
                    $scope.panel.load = true;
                    $scope.panel.empty = false;
                    SocialSecurityService.getPensionInfo()
                        .then(function (info) {
                            var pension = info.pension[0];
                            for (var p in pension) {
                                if (pension.hasOwnProperty(p)) {
                                    $scope.data.pension.push({
                                        title: $scope.PensionMap[p].name,
                                        value: pension[p],
                                        disIndex: $scope.PensionMap[p].disIndex
                                    });
                                }
                            }

                            $scope.data.pension.sort(function (a, b) {
                                return a.disIndex - b.disIndex;
                            });
                            $scope.data.curPension = $scope.data.pension.slice(
                                $scope.control.pl, $scope.control.pl + $scope.limit.pension
                            );
                            if ($scope.data.pension.length > $scope.limit.pension)
                                $scope.control.pa = 'arrow-down';

                            $scope.panel.load = false;
                            $scope.panel.empty = $scope.data.pension.length === 0;
                        });
                };

                // goto medical and get medical info
                $scope.gotoMedical = function (start, end, stay) {
                    start = start || $scope.data.filterDis[0];
                    end = end || $scope.data.filterDis[1];
                    !stay && pageSwitch(2, 0)();

                    $scope.data.medical = [];
                    $scope.data.curMedical = [];
                    $scope.control.ml = 0;
                    $scope.control.ma = '';
                    $scope.panel.load = true;
                    $scope.panel.empty = false;
                    SocialSecurityService.getMedicalInfo(start, end)
                        .then(function (info) {
                            info.medical.forEach(function (m) {
                                $scope.data.medical.push({
                                    title: m['czlx'],
                                    time: new Date(m['czsj']).toISOString().substr(0, 10),
                                    value: m['je'],
                                    state: m['czlx'] === '医保收入'
                                });
                            });
                            $scope.data.curMedical = $scope.data.medical.slice(
                                $scope.control.ml, $scope.control.ml + $scope.limit.medical
                            );
                            if ($scope.data.medical.length > $scope.limit.medical)
                                $scope.control.ma = 'arrow-down--blur';


                            $scope.panel.load = false;
                            $scope.panel.empty = $scope.data.medical.length === 0;
                        });
                };

                // goto retirement and get retirement info
                $scope.gotoRetirement = function () {
                    pageSwitch(3)();
                    $scope.panel.empty = true;
                };

                // gotoUnemployment and get umployment info
                $scope.gotoUnemployment = function () {
                    pageSwitch(4)();
                    $scope.panel.empty = true;
                };
            }

            function pageSwitch(page, pos) {
                page = page || 0;
                return function () {
                    $scope.pageStack.push($scope.control.page);
                    $scope.control.page = page;
                    $scope.cp = $scope.position[$scope.page[$scope.control.page]];
                    if (typeof pos === 'number') resetFocus(pos);
                }
            }

            function resetFocus(pos) {
                pos = pos || 0;
                $scope.focus.ci = $scope.cp[pos]['id'];
            }

            function resetIndex() {
                $scope.control.pl = 0;
                $scope.control.pa = '';
                $scope.control.ml = 0;
                $scope.control.ma = '';
                $scope.data.filterDis = ['201701', '201706'];
                $scope.data.filter = ['', '', '', ''];
            }

            function padding(str, limit) {
                str = str.toString();
                limit = limit || 2;
                for (var i = str.length; i < limit; i++) {
                    str = '0' + str;
                }
                return str;
            }

            function globalAction() {
                if ($scope.control.mf) return;
                var back = function () {
                    event.preventDefault();
                    if ($scope.control.page === 2 && document.activeElement.id !== 'ss-m1') {
                        document.getElementById('ss-m1').focus();
                        $scope.control.ml = 0;
                        $scope.data.curMedical = $scope.data.medical.slice(
                            $scope.control.ml, $scope.control.ml + $scope.limit.medical
                        );
                        $scope.control.ma = 'arrow-down--blur';
                        return;
                    }

                    if ($scope.pageStack.length) {
                        $scope.control.page = $scope.pageStack.pop();
                        $scope.cp = $scope.position[$scope.page[$scope.control.page]];
                        if ($scope.control.page === 0) {
                            $scope.panel.empty = false;
                            resetIndex();
                            resetFocus($scope.pageCache);
                        }
                    } else {
                        $scope.$apply(function () {
                            $location.path('/home').replace();
                        });
                    }
                };
                var up = function () {
                    // pension page
                    if ($scope.control.page === 1) {
                        if ($scope.control.pl > 0) {
                            $scope.data.curPension = $scope.data.pension.slice(
                                --$scope.control.pl, $scope.control.pl + $scope.limit.pension
                            );
                            if ($scope.control.pa && $scope.control.pa !== 'arrow-down')
                                $scope.control.pa = 'arrow-down';
                        }
                    }

                    // medical page
                    if ($scope.control.page === 2) {
                        if ($scope.control.ml > 0) {
                            $scope.data.curMedical = $scope.data.medical.slice(
                                --$scope.control.ml, $scope.control.ml + $scope.limit.medical
                            );
                            if ($scope.control.ma && $scope.control.ma !== 'arrow-down')
                                $scope.control.ma = 'arrow-down';
                        } else {
                            document.getElementById('ss-m1').focus();
                            if ($scope.control.ma)
                                $scope.control.ma = 'arrow-down--blur';
                        }
                    }
                };
                var down = function () {
                    // pension page
                    if ($scope.control.page === 1) {
                        if ($scope.control.pl < $scope.data.pension.length - $scope.limit.pension) {
                            $scope.data.curPension = $scope.data.pension.slice(
                                ++$scope.control.pl, $scope.control.pl + $scope.limit.pension
                            );
                            if ($scope.control.pl + $scope.limit.pension === $scope.data.pension.length)
                                $scope.control.pa = 'arrow-up';
                        }
                    }

                    // medical page
                    if ($scope.control.page === 2) {
                        if ($scope.control.ml < $scope.data.medical.length - $scope.limit.medical) {
                            $scope.data.curMedical = $scope.data.medical.slice(
                                ++$scope.control.ml, $scope.control.ml + $scope.limit.medical
                            );
                            if ($scope.control.ml + $scope.limit.medical === $scope.data.medical.length)
                                $scope.control.ma = 'arrow-up';
                            else
                                $scope.control.ma = 'arrow-down';
                        }
                    }
                };

                switch (event.keyCode) {
                    case KEY.UP:
                        up();
                        break;
                    case KEY.DOWN:
                        down();
                        break;
                    case KEY.BACK:
                        back();
                        break;
                }

                $scope.$digest();
            }

            function moveShim(dir) {
                var curFocus = $scope.cp.filter(function (item) {
                    return item.id === $scope.focus.ci;
                })[0];
                if (curFocus['move'][dir] !== -1) {
                    $scope.focus.ci = curFocus['move'][dir];
                }

                if ($scope.control.page === 0) {
                    $scope.cp.forEach(function (item, index) {
                        if (item.id === $scope.focus.ci) $scope.pageCache = index;
                    });
                }
            }

            $scope.$on('$destroy', function () {
                document.removeEventListener('keydown', globalAction);
            });
        }
    ]
);